package com.wu.shiro;

import com.wu.entity.ShiroUser;
import com.wu.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wuyanshen
 * @date 2019-01-16 11:26 AM
 * @discription 密码重试次数限制
 */
public class MyRetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    private static final Logger log = LoggerFactory.getLogger(MyRetryLimitHashedCredentialsMatcher.class);

    //集群中可能会导致出现验证多过5次的现象，因为AtomicInteger只能保证单节点并发
    private Cache<String, AtomicInteger> loginRetryCache;

    private int maxRetryCount;

    private String loginRetryCacheName;

    public void setMaxRetryCount(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }

    public MyRetryLimitHashedCredentialsMatcher(CacheManager cacheManager, String loginRetryCacheName, Integer maxRetryCount) {
        this.loginRetryCacheName = loginRetryCacheName;
        loginRetryCache = cacheManager.getCache(loginRetryCacheName);
        this.maxRetryCount = maxRetryCount;
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String) token.getPrincipal();
        //retry count + 1
        AtomicInteger retryCount = loginRetryCache.get(username);
        if (null == retryCount) {
            retryCount = new AtomicInteger(0);
            loginRetryCache.put(username, retryCount);
        }
        if (retryCount.incrementAndGet() > maxRetryCount) {
            log.warn("username: " + username + " tried to login more than 5 times in period");
            throw new ExcessiveAttemptsException("username: " + username + " tried to login more than 5 times in period"
            );
        }


        //这里重写了shiro的密码比对,用token中的密码和数据库的密码比对
        boolean matches = false;
        if (token instanceof UsernamePasswordToken) {
            matches = super.doCredentialsMatch(token, info);
        } else {
            ShiroUser user = JwtUtil.getUser(token.getPrincipal().toString());
            if (user.getPassword().equals(info.getCredentials())) {
                matches = true;
            }
        }

        if (matches) {
            //clear retry data
            loginRetryCache.remove(loginRetryCacheName);
        }
        return matches;
    }


}
